import { ApiRes } from './../../types/data.d'
import request from '@/utils/request'
import { CheckoutInfo, UserAddress } from '@/types/checkout.d'
import { defineStore } from 'pinia'
const useCheckoutStore = defineStore({
  id: 'checkout',
  state: () => ({
    checkoutInfo: {} as CheckoutInfo
  }),
  actions: {
    async getCheckoutInfo() {
      const res = await request.get<ApiRes<CheckoutInfo>>('/member/order/pre')
      this.checkoutInfo = res.data.result
      // console.log(this.checkoutInfo, this.checkoutInfo.summary)
    },
    // 添加收货地址(api基地址可以发请求，pci不可)
    async addAddress(address: UserAddress) {
      await request.post('/member/address', address)
      this.getCheckoutInfo()
    },
    // 修改收货地址
    async updateAddress(address: UserAddress) {
      await request.put(`/member/address/${address.id}`, address)
      this.getCheckoutInfo()
    }
  },
  getters: {
    showAddress(): UserAddress | null {
      // 如果没有地址，返回null
      if (this.checkoutInfo.userAddresses.length === 0) {
        return null
      }
      // 如果有地址
      const defaultAddress = this.checkoutInfo.userAddresses.find(
        (item) => item.isDefault === 0
      )
      return defaultAddress
        ? defaultAddress
        : this.checkoutInfo.userAddresses[0]
    }
  }
})

export default useCheckoutStore
